<?php 
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;


use app\admin\model\ResortLog;
use think\Db;

/**
 * 学生报警记录(一天多条)管理-服务类
 * @author 牧羊人
 * @since: 2024/06/25
 * Class ResortLogService
 * @package app\admin\service
 */
class ResortLogService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new ResortLog();
        // 解析Token获取用户ID
        $token = request()->header("Authorization");
        $token = str_replace("Bearer ", null, $token);
        $jwt = new \Jwt();
        $this->userId = $jwt->verifyToken($token);
    }
	
	/**
     * 获取数据列表
     * @return array
     * @since 2024/06/25
     * @author 牧羊人
     */
    public function getList($page = 0, $limit = 0)
    {
        // 查询条件
        $map = [];
        //地区
        $param = request()->param();
        $province_code = getter($param, "province_code");
        $city_code = getter($param, "city_code");
        $district_code = getter($param, "district_code");
        $streets_code = getter($param, "streets_code");
        if($streets_code){
            $map[] = ['schoole.streets_code', '=', $streets_code];
        }elseif ($district_code){
            $map[] = ['schoole.district_code', '=', $district_code];
        }elseif ($city_code){
            $map[] = ['schoole.city_code', '=', $city_code];
        }elseif ($province_code){
            $map[] = ['schoole.province_code', '=', $province_code];
        }
        $schoole_id = request()->param('schoole_id', '');
        if ($schoole_id) {
            $map[] = ["s.schoole_id", "=", $schoole_id];
        }
        $grade_id = request()->param('grade_id', '');
        if ($grade_id) {
            $map[] = ["s.grade_id", "=", $grade_id];
        }
        $status = request()->param('status', '');
        if ($status) {
            $map[] = ["rl.status", "=", $status];
        }
        $class_id = request()->param('class_id', '');
        if ($class_id) {
            $map[] = ["s.class_id", "=", $class_id];
        }
        $gender = request()->param('gender', '');
        if ($gender) {
            $map[] = ["s.gender", "=", $gender];
        }
        $keywords = request()->param('keywords', '');
        if ($keywords) {
            $map[] = ["s.imei|s.name|s.id_card|s.student_no", "like", '%'.$keywords.'%'];
        }
        $belong_time = request()->param('belong_time', '');
        if ($belong_time && strtotime($belong_time)) {
            $belong_time = strtotime($belong_time);
            $map[] = ["rl.belong_time", ">=", $belong_time];
            $map[] = ["rl.belong_time", "<=", $belong_time + 86399];
        }
        $page = $page ?: request()->param('page', 1);
        $limit = $limit ?: request()->param('limit', 20);

        $teacher = getTeacher( $this->userId);
        if($teacher){
            $clsses = Db::table('think_class')->where('find_in_set(' . $teacher['id']. ',teacher_ids)')->select();
            // print_r($clsses);
            if($clsses){
                $map2 = [];
                $map2[]  = ['grade_id','in',array_column($clsses,'grade_id')];
                $map2[]  = ['class_id','in',array_column($clsses,'class_key')];
                $map2[]  = ['schoole_id','in',array_column($clsses,'schoole_id')];
                $stu = Db::table('think_student')->where($map2)->select();
                //$map[] = ['s.id','in',array_column($stu,'id')];
            }
        }

        $schoolRole = SchoolRoleMap($this->userId,'s.id');
        if($schoolRole){
          //  $map[] = $schoolRole;
        }

       /* $data = db('student')
            ->alias('s')
            ->field('rl.id,s.id as student_id,s.imei,s.avatar,s.name,in_time,out_time,s.student_no,s.id_card,s.gender,s.grade_id,s.class_id,s.schoole_id,s.phone,s.relatives_phone,s.sim_no, schoole.title as schoole_name, grade.title as grade_name, class.title as class_name, rl.create_time, rl.da_type, rl.da_type, dat.name as da_type_name,rl.status,rl.update_time')
            ->join('schoole schoole', 's.schoole_id = schoole.id', 'left')
            ->join('grade grade', 's.grade_id = grade.grade_key', 'left')
            ->join('class class', 's.class_id = class.class_key', 'left')
            ->join('resort_log rl', 's.id = rl.student_id', 'right')
            ->join('device_alarm_type dat', 'dat.id = rl.da_type', 'left')
            ->where($map)
            ->order('rl.id desc')
            ->paginate($limit)
            ->toArray();*/
            $data = db('resort_log')->alias('rl')
                ->field('rl.id,s.id as student_id,s.imei,s.avatar,s.name,in_time,out_time,s.student_no,s.id_card,s.gender,s.grade_id,s.class_id,s.schoole_id,s.phone,s.relatives_phone,s.sim_no, schoole.title as schoole_name,rl.create_time, rl.da_type, rl.da_type, dat.name as da_type_name,rl.status,rl.update_time')
                ->join('student s', 'rl.student_id = s.id', 'left')
                ->join('schoole schoole', 's.schoole_id = schoole.id', 'left')
                ->join('device_alarm_type dat', 'dat.id = rl.da_type', 'left')
                ->where($map)
                ->order('rl.id desc')
                ->paginate($limit)
                ->toArray();;
                foreach ($data['data'] as &$value){
                    $grade_name = Db::table('think_grade')->where('schoole_id',$value['schoole_id'])->where('grade_key',$value['grade_id'])
                        ->value('title');
                    $value['grade_name'] = $grade_name;
                    $class_name = Db::table('think_class')->where('schoole_id',$value['schoole_id'])
                        ->where('grade_id',$value['grade_id'])
                        ->where('class_key',$value['class_id'])
                        ->value('title');
                    $value['class_name'] = $class_name;
                }
        $res = [
            "msg" => '操作成功',
            "code" => 0,
            "count" => $data['total'],
            "data" => $data['data'],
        ];
        return $res;
    }

    //编辑 是否已处理
    public function edit()
    {
        // 请求参数
        request()->filter('trim');
        $data = request()->param();
        $id = getter($data, "id", 0);// ID
        if(!$id){
            return message("缺少id", false);
        }
        if(!isset($data['schoole_id']) || !$data['schoole_id']){
            return message("缺少schoole_id", false);
        }
        //查询报警记录
        $info = db('resort_log')->where(['id' => $id])->find();
        if(!$info) return message("报警记录不存在", false);

        //验证学生
        $student = db('student')->where(['schoole_id' => $data['schoole_id'], 'id' => $info['student_id']])->find();
        if(!$student) return message("非法操作", false);

        if(!isset($data['status']) || !in_array($data['status'], [0, 1])){
            return message("缺少status", false);
        }

        $update_data['id'] = $data['id'];
        $update_data['status'] = $data['status'];
        $error = '';
        $result = $this->model->edit($update_data, $error);
        if (!$result) {
            return message($error, false);
        }
        return message();
    }

    /**
     * 导出Excel
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function exportExcel()
    {
        set_time_limit(0);
        $export_type = request()->param('export_type', 0);
        $schoole_id = request()->param('schoole_id', '');
        $schoole_name = '';

        // 获取导出的数据源
        $res = $this->getList(1, 50000);
        $list = $res['data'];

        // 实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        // 激活当前的sheet表
        $activeSheet = $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $activeSheet->setCellValue('A1', '姓名')
            ->setCellValue('B1', '学号')
            ->setCellValue('C1', '')
            ->setCellValue('D1', '性别')
            ->setCellValue('E1', '学校')
            ->setCellValue('F1', '年级')
            ->setCellValue('G1', '班级')
            ->setCellValue('H1', '报警内容')
            ->setCellValue('I1', '是否已处理')
            ->setCellValue('J1', '处理时间')
            ->setCellValue('K1', '报警时间');

        // 设置单元格宽度
        $activeSheet->getColumnDimension('A')->setWidth(20);
        $activeSheet->getColumnDimension('B')->setWidth(20);
        $activeSheet->getColumnDimension('C')->setWidth(0);
        $activeSheet->getColumnDimension('D')->setWidth(20);
        $activeSheet->getColumnDimension('E')->setWidth(20);
        $activeSheet->getColumnDimension('F')->setWidth(20);
        $activeSheet->getColumnDimension('G')->setWidth(20);
        $activeSheet->getColumnDimension('H')->setWidth(20);
        $activeSheet->getColumnDimension('I')->setWidth(20);
        $activeSheet->getColumnDimension('J')->setWidth(20);
        $activeSheet->getColumnDimension('K')->setWidth(20);

        //'rl.id,s.id as student_id,s.imei,s.avatar,s.name,s.student_no,s.id_card,s.gender,s.grade_id,s.class_id,s.schoole_id,s.phone,s.relatives_phone,s.sim_no, schoole.title as schoole_name, grade.title as grade_name, class.title as class_name, rl.create_time, rl.da_type, rl.da_type, dat.name as da_type_name,rl.status'
        // 循环刚取出来的数组，将数据逐一添加到excel表格
        $gender_arr = [
            '1' => '男',
            '2' => '女',
        ];
        for ($i = 0; $i < count($list); $i++) {
            $gender = $gender_arr[$list[$i]['gender']] ?? '';
            $status = $list[$i]['status'] ? '已处理' : '未处理';
            $update_time = $list[$i]['update_time'] ? date('Y-m-d H:i:s', $list[$i]['update_time']) : '/';
            $create_time = date('Y-m-d H:i:s', $list[$i]['create_time']);
            $activeSheet->setCellValue('A' . ($i + 2), $list[$i]['name']);
            $activeSheet->setCellValue('B' . ($i + 2), $list[$i]['student_no']);
            $activeSheet->setCellValue('C' . ($i + 2), '');
            $activeSheet->setCellValue('D' . ($i + 2), $gender);
            $activeSheet->setCellValue('E' . ($i + 2), $list[$i]['schoole_name']);
            $activeSheet->setCellValue('F' . ($i + 2), $list[$i]['grade_name']);
            $activeSheet->setCellValue('G' . ($i + 2), $list[$i]['class_name']);
            $activeSheet->setCellValue('H' . ($i + 2), $list[$i]['da_type_name']);
            $activeSheet->setCellValue('I' . ($i + 2), $status);
            $activeSheet->setCellValue('J' . ($i + 2), $update_time);
            $activeSheet->setCellValue('K' . ($i + 2), $create_time);
            $schoole_name = $list[$i]['schoole_name'];
        }
        // 设置保存的Excel表格名称
        $filename = $schoole_name . '_学生报警记录导出_' . date('YmdHis', time()) . ".xlsx";
        // 设置当前激活的sheet表格名称
        $activeSheet->setTitle('Sheet1');

        if($export_type) {//直接浏览器输出
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $filename);
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');
            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
            return;
        }

        // 保存本地文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $file_dir = UPLOAD_TEMP_PATH . "/" . $schoole_id . "/";
        $savePath = $file_dir . $filename;
        // 检测文件路径是否存在,不存在则创建
        if (!file_exists($file_dir)) {
            mkdirs($file_dir, 0777, true);
        }
        $objWriter->save($savePath);

        // 文件地址
        $filePath = get_image_url(str_replace(PUBLIC_PATH, "", $savePath));
        return message("操作成功", true, $filePath);
    }
}